package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"yk1-assistant/caches"
	"yk1-assistant/models"
)

func ListOrder(c *gin.Context) {
	var list []models.OrderList
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "2"))
	offset := (page - 1) * pageSize
	redis_key := "order_list" + strconv.Itoa(page)
	cacheData, _ := caches.Rdb.Get(caches.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").Select(
			"cars.car_code AS CarCode",
			"cars.car_name AS CarName",
			"cars.car_num AS CarNum",
			"orders.id AS OrderId",
			"orders.order_no AS OrderNo",
			"orders.order_from AS OrderFrom",
			"orders.order_to AS OrderTo",
		).Joins("LEFT JOIN cars ON cars.id = orders.cid").
			Offset(offset).Limit(pageSize).Debug().Find(&list)
		jsonData, _ := json.Marshal(&list)
		caches.Rdb.Set(caches.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	models.DB.Table("orders").Select(
		"cars.car_code AS CarCode",
		"cars.car_name AS CarName",
		"cars.car_num AS CarNum",
		"orders.id AS OrderId",
		"orders.order_no AS OrderNo",
		"orders.order_from AS OrderFrom",
		"orders.order_to AS OrderTo",
	).Joins("LEFT JOIN cars ON cars.id = orders.cid").
		Offset(offset).Limit(pageSize).Debug().Find(&list)
	var total int64
	models.DB.Model(&models.Order{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  list,
		"total": total,
	})
	return
}
func AddCar(c *gin.Context) {
	car_code := c.PostForm("car_code")
	car_name := c.PostForm("car_name")
	car_num, _ := strconv.Atoi(c.PostForm("car_num"))
	data := models.Car{

		CarCode: car_code,
		CarName: car_name,
		CarNum:  car_num,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func AddOrder(c *gin.Context) {
	order_no := c.PostForm("order_no")
	order_from := c.PostForm("order_from")
	order_to := c.PostForm("order_to")
	cid, _ := strconv.Atoi(c.PostForm("car_num"))
	data := models.Order{

		OrderNo:   order_no,
		OrderFrom: order_from,
		OrderTo:   order_to,
		Cid:       cid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
